<template>
  <div class="container">
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item prop="name">
        <el-input
          v-model="ruleForm.name"
          placeholder="请输入用户名"
        />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          placeholder="密码"
        />
      </el-form-item>

      <el-form-item prop="school">
        <el-input
          v-model="ruleForm.school"
          placeholder="学校"
        />
      </el-form-item>

      <el-form-item prop="nickname">
        <el-input
          v-model="ruleForm.nickName"
          placeholder="昵称"
        />
      </el-form-item>

      <el-form-item prop="age">
        <el-input
          v-model="ruleForm.age"
          placeholder="年龄"
        />
      </el-form-item>

      <el-form-item prop="gender">
        <el-input
          v-model="ruleForm.gender"
          placeholder="性别"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
        >
          注 册
        </el-button>
        <el-button @click="resetForm('ruleForm')">
          重 置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    const validateName = (rule, value, callback) => {
      const regex = /^[\u4e00-\u9fa5a-zA-Z]{6,}$/;
      if (!regex.test(value)) {
        callback(new Error('要6位以上中英文哦！'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        name: '',
        password: '',
        school: '',
        age: '',
        nickName: '',
        gender: '',
      },
      rules: {
        name: [{ validator: validateName, trigger: 'blur' }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            message: '要6位以上才行哦！',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            await this.$request({
              url: '/api/user/regist',
              method: 'post',
              data: {
                username: this.ruleForm.name,
                password: this.ruleForm.password,
                age: this.ruleForm.age,
                school: this.ruleForm.school,
                nickname: this.ruleForm.nickName,
                gender: this.ruleForm.gender,
              },
            });
            this.$router.push('/login');
          } catch (e) {
            this.$message.error('滚蛋！');
          }
        }
        return false;
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
.container {
  width: 500px;
}
</style>
